# from __future__ import absolute_import, unicode_literals

from celery import shared_task
from tools.myredis import r
from myapp.models import Orders

@shared_task
def cancelorders():
    print("取消订单")
    
@shared_task  
def setdoctor():
    # 3.从队列中取出订单号，根据订单号查询订单
    # 4.根据订单中科室查找医生列表
    # 5.hash取模均衡分配
    # 6.更新订单表中医生id
    print('给患者分配医生')
    # 查询队列中的订单号，根据订单号查询科室，根据科室查询医生，写入医生患者表
    len = r.list_len('doctorlist')
    if len>0:
        data = r.list_all('doctorlist')
        # rpoplpush  list1  list2中  1001,1002
        # 更新订单
        # 删除list2

        for i in data:
            orderno = i.decode()
            orders = Orders.objects.filter(orderno=orderno).first()
            deptid = orders.department
            #查询此科室下医生数据
            dockers = doctor.objects.filter(deptid=deptid).all()
            dlist=[i.id for i in dockers]
            #查询医生个数
            count = doctor.objects.filter(deptid=deptid).count()
            #用订单号和总个数hash取
            number = hash(orderno)%count
            dockerid = dlist[number]
            # 创建一张表， userid  dockerid  患者id  状态
            #写入医生患者表
            # 从队列中删除订单号
import requests,json         
@shared_task              
def getbaidu():
    #查询队列中10个数据
    #从redis中取count判断，如果count不存在或者count为0
    count = r.str_get('bdcount')
    if count >0:
        return;
    piclist = r.list_all('bdapilist',0,10)
    #在redis中加入count 10
    r.str_set('bdcount',10)
    for i in piclist:
        picurl = i.decode()
        url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + get_access_token()
        payload='id_card_side=front&url='+picurl+'&detect_ps=false&detect_risk=false&detect_quality=false&detect_photo=false&detect_card=false&detect_direction=false'
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        
        response = requests.request("POST", url, headers=headers, data=payload)
        data = json.loads(response)
        name = data['words_result'][0]['words']
        code = data['words_result'][1]['words']
        #把数据存入redis中
        r.str_set(picurl,json.dumps({"name":name,'code':code}))
        #从队列中删除信息
        r.list_delvalue('bdapilist',picurl)
        #把redis中的count -1
        r.int_jian('bdcount')
   
   


